/**
 * Created by King_Vicent on 2018/7/15.
 */
var vm = new Vue({
    el: '#rrapp',
    data() {
        oneLevelNum = 0;
        oneLevelNumToAdd = 0;
        return {
            q: {
                mbmc: null
            },
            onAll: 'primary',
            onDefault: '',
            onDiy: '',
            onDaily: '',
            showList: true, // 表格页面是否显示
            viewList: false, // 查看页面是否显示
            editList: false, // 新增页面是否显示
            isAdd: false, // 新增
            isEdit: false, // 编辑
            mblb: null,//查看模板类别
            title: null,
            superviseTemplet: {},
            rightTtitle: '模板预览',
            addTitle: '模板新增',
            tableData: [], // 表格数据
            pageNo: 1, // 当前页
            totalPage: 0, // 总页数
            pageSize: 10, // 每页数据条数
            viewTitle: '', // 查看时的模板标题
            publicActiveId: '', // 左侧模板标识为选中状态的id
            addTplTitle: '新建模板', // 新增时的模板名
            props: {
                children: 'children',
                label: 'label'
            },
            lookId: "",
            lookTitle: "",
            lookTime: "",
            lookCorp: "",
            lookStatus: "",
            lookCheck: false,
            lookUpdateCheck: false,
            viewData: [], // 查看时 模板问题
            viewDataForEdit: [], // 供修改使用的数据，在取消后不会影响原数据
            viewExpandedKeys: [], // 查看时 展开的树节点
            checkedData: [], // 编辑（新增）时 选中的模板问题
            checkedExpandedKeys: [], // 编辑（新增）时 展开的树节点
            problemData: [], // 所有问题
            problemExpandedKeys: [], // 编辑时展开的树节点
            problemCheckedKeys: [], // 编辑时选中的树节点
            checkedKeys: [], // 编辑时选中的问题
            halefCheckedKeys: [], // 编辑时半选的问题
            // 中间 模板详情
            levelClass: '1.', // 级别class（所有模板项，根据levelNum添加不同等级的class来改变样式）
            newTplName: '', // 新增模板的名字
            mblx: '1', // 新增模板的类型
            mblxList: [
                {
                    label: '自定义模板',
                    value: '1'
                },
                {
                    label: '每日必查模板',
                    value: '3'
                }
            ],
            templetInfoDataAdd: [], // (新增模板预览所有 选中的模板问题，根据levelNum添加不同等级的class来改变样式）
            ids: [], // 新增id
        }
    },
    mounted() {
        oneLevelNum = 0;
        oneLevelNumToAdd = 0;
        this.getTableData();
        this.getStandardlistData();
    },
    filters: {
        formatterLevel: function (val) {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            switch (val) {
                case '1':
                    return 'first-level'
                    break
                case '2':
                    return 'second-level'
                    break
                case '3':
                    return 'third-level'
                    break
                case '4':
                    return 'fourth-level'
                    break
            }
        }

    },
    methods: {

        formatStatus: function (row, column) {
            if (row.mblx === '0') {
                // return '<span style="color: #00a65a" >使用中</span>';
                return '使用中';
            }
            return row.status === '0' ?
                '未使用' :
                '使用中';
            /* if (row.mblx === '0') {
             return '<span style="color: #00a65a" >使用中</span>';
             }
             return row.status === '0' ?
             '<span >未使用</span>' :
             '<span style="color: #00a65a" >使用中</span>';*/
            // return row.status == 1 ? '男' : row.sex == 0 ? '女' : '未知';
        },

        formatStandardType: function (row, column) {
            if (row.mblx === '0') {
                if (row.standardType === '1') {
                    return "标准模板-队伍管理"
                }
                if (row.standardType === '2') {
                    return "标准模板-执法执勤"
                }
                if (row.standardType === '3') {
                    return "标准模板-社会面管控"
                }
                if (row.standardType === '4') {
                    return "标准模板-其他问题"
                }

            } else if (row.mblx === '1') {
                return "自定义模板";
            } else if (row.mblx === '3') {
                return "每日必查模板";
            } else {
                return "";
            }
        },

        formatCorp: function (row, column) {
            return row.mblx === '0' ?
                '系统生成' :
                row.shijdm;
        },

        formatTime: function (row, column) {
            return dateFtt("yyyy/MM/dd", new Date(row.createTime));
        },

        //获取表格数据
        getTableData: function () {
            let url = 'business/supervisetemplet/list';
            let params = {
                mbmc: this.q.mbmc,
                mblx: this.mblb,
                page: this.pageNo
            }
            $.ajax({
                type: "POST",
                url: baseURL + url,
                dataType: 'json',
                data: params,
                success: function (res) {
                    if (res.code === '0') {
                        vm.tableData = res.page.list
                        vm.totalPage = res.page.totalPage
                        vm.pangeNo = res.page.currPage
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },
        // 取消添加模板
        cancelAddTpl: function () {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            vm.isAdd = !vm.isAdd;
            vm.showList = true;
            vm.rightTtitle = '模板预览';
            vm.addTplTitle = '新增模板'
            vm.checkedData = []
            vm.newTplName = ''; // 新增模板的名字
            vm.mblx = '1'; // 新增模板的类型
            vm.templetInfoDataAdd = [];// 模板预览（一级列表）重置
            // vm.templetInfoSecondDataAdd = [] // 模板预览（二级列表）重置
            // vm.templetInfoThirdDataAdd = [] // 模板预览（三级列表）重置
            vm.ids = []// 新增id重置
        },
        // 表格查看模板
        handleView: function (index, row) {
            vm.viewList = true
            vm.showList = false
            vm.editList = false
            vm.mblx=row.mblx
            vm.lookTitle = row.mblx === '0' ? '系统生成' : row.shijdm
            vm.lookTime = dateFtt("yyyy-MM-dd", new Date(row.createTime))
            vm.lookCorp = row.shijdm
            vm.lookId = row.id
            if (row.mblx === '0') {
                // return '<span style="color: #00a65a" >使用中</span>';
                vm.lookStatus = '使用中';
            } else {
                vm.lookStatus = row.status === '0' ?
                    '未使用' :
                    '使用中';
            }
            if (row.mblx === '0') {
                vm.lookUpdateCheck = false
            } else {
                vm.lookUpdateCheck = true
            }
            if (row.mblx === '3' && row.status == '0') {
                vm.lookCheck = true
            } else {
                vm.lookCheck = false

            }

            vm.viewModelInfo(row.id, row.mblx, row.mbmc)
        },

        // 获取要查看模板的信息
        viewModelInfo: function (id, type, tplName) {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            let url = 'business/supervisetemplet/findModelStandardListTree?id=' + id
            $.ajax({
                type: "GET",
                url: baseURL + url,
                contentType: "application/json",
                success: function (res) {
                    if (res.code === '0') {
                        vm.viewTitle = tplName
                        vm.viewData = res.list
                        vm.viewDataForEdit = res.list
                        vm.publicActiveId = id
                        oneLevelNum = 0
                        oneLevelNumToAdd = 0
                        vm.viewExpandedKeys = []
                        for (var i in vm.viewData) {
                            var first = vm.viewData[i]
                            vm.viewExpandedKeys.push(first.id)
                            if (first.children !== []) {
                                for (var j in first.children) {
                                    var second = first.children[j]
                                    vm.viewExpandedKeys.push(second.id)
                                    if (second.children !== []) {
                                        for (var k in second.children) {
                                            var third = second.children[k]
                                            if (third.children !== []) {
                                                vm.viewExpandedKeys.push(third.id)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },
        indexMethod(index) {
            return (vm.pageNo - 1) * vm.pageSize + (index + 1);
        },
        // 分页
        pageChange: function () {
            debugger
            vm.getTableData()
            /*let params = {
                mbmc: vm.q.mbmc,
                mblx: vm.mblb,
                pageNo: vm.pageNo
            }
            let url = 'business/supervisetemplet/list';
            debugger
            $.ajax({
                type: "POST",
                url: baseURL + url,
                dataType:'json',
                data: params,
                success: function (res) {
                    if (res.code === '0') {
                        vm.tableData = res.page.list
                        vm.totalPage = res.page.totalPage
                        vm.pangeNo = res.page.currPage
                    } else {
                        alert(res.msg);
                    }
                }
            });*/
        },

        // 选择表格数据类型
        checkMblb: function (mblb) {
            vm.mblb = mblb;
            if (mblb === null) {
                vm.onAll = 'primary'
                vm.onDefault = ''
                vm.onDiy = ''
                vm.onDaily = ''
            } else if (mblb === 0) {
                vm.onAll = ''
                vm.onDefault = 'primary'
                vm.onDiy = ''
                vm.onDaily = ''
            } else if (mblb === 1) {
                vm.onAll = ''
                vm.onDefault = ''
                vm.onDiy = 'primary'
                vm.onDaily = ''
            } else if (mblb === 3) {
                vm.onAll = ''
                vm.onDefault = ''
                vm.onDiy = ''
                vm.onDaily = 'primary'
            }
            vm.reload();
        },

        // 查询
        query: function () {
            vm.reload();
        },

        // 查询刷新数据
        reload: function () {
            vm.viewList = false
            vm.showList = true
            vm.editList = false

            vm.getTableData();
        },

        //获取所有问题数据
        getStandardlistData: function () {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            let url = 'business/supervisestandard/findAllListTree';
            $.ajax({
                type: "GET",
                url: baseURL + url,
                contentType: "application/json",
                success: function (res) {
                    if (res.code === '0') {
                        vm.problemData = res.list;
                        // vm.halefCheckedKeys = [2, 3, 4] // 获取半选key
                        // vm.checkedKeys = [9] // 获取选中数据
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },

        // 选择问题
        handleCheckChange(data, checked, indeterminate) { // arguments:对象、节点本身是否被选中、节点的子树中是否有被选中的节点
            var halfCheckedNodes = vm.$refs.problemTree.getHalfCheckedNodes() // 获取半选数据
            var halfCheckedKeys = vm.$refs.problemTree.getHalfCheckedKeys() // 获取半选id
            var checkedNodes = vm.$refs.problemTree.getCheckedNodes() // 获取选中数据
            var checkedKeys = vm.$refs.problemTree.getCheckedKeys() // 获取选中id

            var halfCheckedData = halfCheckedNodes // 定义新半选变量不操作原数据
            var checkedData = checkedNodes // 定义新选中变量不操作原数据

            var firstData = []
            var secondData = []
            var thirdData = []
            var fourthData = []

            // 将半选的问题放入各级数组
            for (var i in halfCheckedData) {
                if (halfCheckedData[i].levelNum == 1) {
                    firstData.push({
                        id: halfCheckedData[i].id,
                        label: halfCheckedData[i].label,
                        pId: 0,
                        children: [],
                        levelNum: 1
                    })
                } else if (halfCheckedData[i].levelNum == 2) {
                    secondData.push({
                        id: halfCheckedData[i].id,
                        label: halfCheckedData[i].label,
                        pId: halfCheckedData[i].pId,
                        children: [],
                        levelNum: 2
                    })
                } else if (halfCheckedData[i].levelNum == 3) {
                    thirdData.push({
                        id: halfCheckedData[i].id,
                        label: halfCheckedData[i].label,
                        pId: halfCheckedData[i].pId,
                        children: [],
                        levelNum: 3
                    })
                } else {
                    fourthData.push({
                        id: halfCheckedData[i].id,
                        label: halfCheckedData[i].label,
                        pId: halfCheckedData[i].pId,
                        children: [],
                        levelNum: 4
                    })
                }
            }
            // 将选中的问题放入各级数组
            for (var i in checkedData) {
                if (checkedData[i].levelNum == 1) {
                    firstData.push({
                        id: checkedData[i].id,
                        label: checkedData[i].label,
                        pId: 0,
                        children: [],
                        levelNum: 1
                    })
                } else if (checkedData[i].levelNum == 2) {
                    secondData.push({
                        id: checkedData[i].id,
                        label: checkedData[i].label,
                        pId: checkedData[i].pId,
                        children: [],
                        levelNum: 2
                    })
                } else if (checkedData[i].levelNum == 3) {
                    thirdData.push({
                        id: checkedData[i].id,
                        label: checkedData[i].label,
                        pId: checkedData[i].pId,
                        children: [],
                        levelNum: 3
                    })
                } else {
                    fourthData.push({
                        id: checkedData[i].id,
                        label: checkedData[i].label,
                        pId: checkedData[i].pId,
                        children: [],
                        levelNum: 4
                    })
                }
            }

            // 对每个等级的数组进行排序
            function compare(property) {
                return function (arg1, arg2) {
                    var value1 = arg1[property];
                    var value2 = arg2[property];
                    return value1 - value2;
                }
            }

            firstData.sort(compare('id'))
            secondData.sort(compare('id'))
            thirdData.sort(compare('id'))
            fourthData.sort(compare('id'))

            // 将半选的fourthData放入对应的thirdData内
            for (var i in fourthData) {
                var pId = fourthData[i].pId
                for (var j in thirdData) {
                    if (thirdData[j].id === pId) {
                        thirdData[j].children.push({
                            id: fourthData[i].id,
                            label: fourthData[i].label,
                            pId: fourthData[i].pId,
                            children: [],
                            levelNum: 4
                        })
                    }
                }
            }
            // 将半选的thirdData放入对应的secondData内
            for (var i in thirdData) {
                var pId = thirdData[i].pId
                for (var j in secondData) {
                    if (secondData[j].id === pId) {
                        secondData[j].children.push({
                            id: thirdData[i].id,
                            label: thirdData[i].label,
                            pId: thirdData[i].pId,
                            children: thirdData[i].children || [],
                            levelNum: 3
                        })
                    }
                }
            }
            // 将半选的secondData放入对应的firstData内
            for (var i in secondData) {
                var pId = secondData[i].pId
                for (var j in firstData) {
                    if (firstData[j].id === pId) {
                        firstData[j].children.push({
                            id: secondData[i].id,
                            label: secondData[i].label,
                            pId: secondData[i].pId,
                            children: secondData[i].children || [],
                            levelNum: 2
                        })
                    }
                }
            }

            vm.checkedData = firstData
            vm.ids = halfCheckedKeys.concat(checkedKeys)
        },

        // 点击添加按钮
        addTpl: function () {
            oneLevelNum = 0
            oneLevelNumToAdd = 0
            vm.addTitle = '模板新增'
            vm.addTplTitle = '新增模板'
            vm.mblx='1'
            vm.isAdd = true
            vm.isEdit = false
            vm.rightTtitle = '选择问题项'
            vm.viewList = false
            vm.showList = false
            vm.editList = true
        },

        // 取消添加模板(编辑模板)
        cancel: function (flag) {
            oneLevelNum = 0
            oneLevelNumToAdd = 0
            vm.isAdd = false
            vm.isEdit = false
            vm.editList = false
            vm.checkedData = []
            vm.addTplTitle = '新增模板'
            if (flag === 'edit') { // 编辑时的取消
                vm.viewList = true
                vm.showList = false
                vm.checkedData = vm.viewDataForEdit
            } else if (flag === 'add') { // 新增时的取消
                vm.viewList = false
                vm.showList = true
            } else {
                vm.viewList = false
                vm.showList = true
            }
            vm.checkedExpandedKeys = []
            vm.problemCheckedKeys = []
            vm.problemExpandedKeys = []
            vm.newTplName = ''; // 新增模板的名字
            vm.mblx = '1'; // 新增模板的类型
            vm.templetInfoDataAdd = [];// 模板预览（一级列表）重置
            vm.ids = []// 新增id重置
        },

        // 启用(禁用)模板
        updateStatus: function () {
            layer.confirm("是否确定启用该模板？", function (index) {
                let data = {'id': vm.lookId}
                let url = 'business/supervisetemplet/updateStatus'
                $.ajax({
                    type: "post",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function (res) {
                        debugger
                        if (res.code === '0') {
                            //请求成功刷新页面数据
                            vm.getTableData();
                            vm.cancelAddTpl()
                        } else {
                            layer.confirm(res.msg + "是否确定启用该模板", function (index) {
                                $.ajax({
                                    type: "post",
                                    url: baseURL + 'business/supervisetemplet/updateStatusConfirm',
                                    contentType: "application/json",
                                    data: JSON.stringify(data),
                                    success: function (res) {
                                        if (res.code === '0') {
                                            //请求成功刷新页面数据
                                            vm.getTableData();
                                            vm.cancelAddTpl()
                                        }
                                        layer.close(index);
                                    }
                                });

                            });
                        }
                        layer.close(index);
                    }
                });
            });
        },

        // 删除模板
        deleteTemplet: function () {
            layer.confirm("是否确定删除该模板？", function (index) {
                let url = 'business/supervisetemplet/delete?id=' + vm.lookId;

                $.ajax({
                    type: "GET",
                    url: baseURL + url,
                    success: function (res) {
                        if (res.code === '0') {
                            //请求成功刷新页面数据
                            vm.getTableData();
                            vm.cancelAddTpl()
                        } else {
                            alert(res.msg);
                        }
                        layer.close(index);
                    }
                });
            });
        },

        // 编辑模板
        editTpl: function () {
            vm.isAdd = false
            vm.isEdit = true
            vm.addTplTitle = vm.viewTitle
            vm.addTitle = '模板修改'
            // vm.lookTitle=""
            vm.checkedData = vm.viewDataForEdit
            // 重置选中、展开的树节点
            vm.checkedExpandedKeys = []
            vm.problemCheckedKeys = []
            vm.problemExpandedKeys = []
            for (var i in vm.checkedData) {
                var first = vm.checkedData[i]
                vm.checkedExpandedKeys.push(first.id)
                if (first.children !== []) {
                    for (var j in first.children) {
                        var second = first.children[j]
                        vm.checkedExpandedKeys.push(second.id)
                        if (second.children !== []) {
                            for (var k in second.children) {
                                var third = second.children[k]
                                if (third.children !== []) {
                                    vm.checkedExpandedKeys.push(third.id)
                                    vm.problemCheckedKeys.push(third.id)
                                }
                            }
                        }
                    }
                }
            }
            for (var i in vm.problemData) {
                var first = vm.problemData[i]
                vm.problemExpandedKeys.push(first.id)
                if (first.children !== []) {
                    for (var j in first.children) {
                        var second = first.children[j]
                        vm.problemExpandedKeys.push(second.id)
                        if (second.children !== []) {
                            for (var k in second.children) {
                                var third = second.children[k]
                                if (third.children !== []) {
                                    vm.problemExpandedKeys.push(third.id)
                                }
                            }
                        }
                    }
                }
            }
            vm.editList = true
            vm.viewList = false
        },

        // 新增时切换模板类型
        changeMblx: function (val) {
            console.log('当前模板类型:' + val)
            console.log('当前模板类型参数为:' + vm.mblx)
        },

        // 确定添加模板
        comfirmAddTpl: function () {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            layer.confirm("是否确定添加模板？", function (index) {
                //请求
                let url = 'business/supervisetemplet/save';
                let params = {};
                //两个值都没取到
                params.mbmc = vm.addTplTitle;
                // params.mbmc = vm.newTplName;
                params.mbwtx = vm.ids.toString();
                params.mblx = vm.mblx;//模板类型 1：自定义模板 3：每日必查模板  只能是这两个的一个
                // console.log(vm.ids)
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(params),
                    success: function (res) {
                        layer.close(index)
                        if (res.code === '0') {
                            //请求成功刷新页面数据
                            //回调函数执行的方法
                            vm.getTableData();
                            vm.cancelAddTpl()
                            // vm.isDaily = false
                        } else {
                            alert(res.msg);
                        }
                    }
                });
            });
        },

        // 修改模板
        comfirmUpdateTpl: function () {
            oneLevelNum = 0;
            oneLevelNumToAdd = 0;
            layer.confirm("是否确定修改模板？", function (index) {
                //请求
                let url = 'business/supervisetemplet/update';
                let params = {};
                //两个值都没取到
                params.mbmc = vm.addTplTitle;
                params.id = vm.lookId;
                // params.mbmc = vm.newTplName;
                params.mbwtx = vm.ids.toString();
                params.mblx = vm.mblx;//模板类型 1：自定义模板 3：每日必查模板  只能是这两个的一个
                // console.log(vm.ids)
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(params),
                    success: function (res) {
                        layer.close(index)
                        if (res.code === '0') {
                            //请求成功刷新页面数据
                            //回调函数执行的方法
                            vm.getTableData();
                            vm.cancelAddTpl()
                            // vm.isDaily = false
                        } else {
                            alert(res.msg);
                        }
                    }
                });
            });
        }
    }
});
var oneLevelNum = 0;
var twoLevelNum = 0;
var threeLevelNum = 0;
var fourLevelNum = 0;

Vue.filter('getSerialNum', function (value) {
    switch (value) {
        case '1':
            oneLevelNum++;
            twoLevelNum = 0;
            threeLevelNum = 0;
            fourLevelNum = 0;
            return oneLevelNum + ".";
            break
        case '2':
            twoLevelNum++;
            threeLevelNum = 0;
            fourLevelNum = 0;
            return oneLevelNum + "." + twoLevelNum + ".";
            break
        case '3':
            threeLevelNum++;
            fourLevelNum = 0;
            return oneLevelNum + "." + twoLevelNum + "." + threeLevelNum + ".";
        case '4':
            fourLevelNum++;
            return oneLevelNum + "." + twoLevelNum + "." + threeLevelNum + "." + fourLevelNum + ".";
            break
    }
});
var oneLevelNumToAdd = 0;
var twoLevelNumToAdd = 0;
var threeLevelNumToAdd = 0;
var fourLevelNumToAdd = 0;
Vue.filter('getSerialNumToAdd', function (value) {
    switch (value) {
        case '1':
            oneLevelNumToAdd++;
            twoLevelNumToAdd = 0;
            threeLevelNumToAdd = 0;
            fourLevelNumToAdd = 0;
            return oneLevelNumToAdd + ".";
            break
        case '2':
            twoLevelNumToAdd++;
            threeLevelNumToAdd = 0;
            fourLevelNumToAdd = 0;
            return oneLevelNumToAdd + "." + twoLevelNumToAdd + ".";
            break
        case '3':
            threeLevelNumToAdd++;
            fourLevelNumToAdd = 0;
            return oneLevelNumToAdd + "." + twoLevelNumToAdd + "." + threeLevelNumToAdd + ".";
        case '4':
            fourLevelNumToAdd++;
            return oneLevelNumToAdd + "." + twoLevelNumToAdd + "." + threeLevelNumToAdd + "." + fourLevelNumToAdd + ".";
            break
    }
});